//TCPTransFileTest.java
package com.ylaihui.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTransFileTest2 {
    @Test
    public void serverTest2() throws IOException {
        ServerSocket serverSocket = new ServerSocket(65500);

        Socket socket = serverSocket.accept();

        // 读入客户端的文件流
        InputStream inputStream = socket.getInputStream();

        //读入文件并写文件到本地的流
        FileOutputStream fileOutputStream = new FileOutputStream(new File("tcp-copy.png"));

        //读取客户端的文件，并写文件到本地
        byte[] bytes = new byte[500];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1){
            //System.out.println("read from client and write to local");
            fileOutputStream.write(bytes,0,len);
        }
        System.out.println("write to local completed");

        // 反馈给客户端，文件已经在服务端完成保存
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("server write file to localhost complete".getBytes());

        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
    @Test
    public void clientTest2() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 65500);

        OutputStream os = socket.getOutputStream();

        // 客户端读取本地文件，并将文件写入到 socket 输出流
        FileInputStream fis = new FileInputStream(new File("tcp.png"));
        byte[] bytes = new byte[500];
        int len = 0;
        while((len = fis.read(bytes)) != -1){
            //System.out.println("read local file and write to server");
            os.write(bytes,0,len);
        }
        System.out.println("write to server completed");
        //告诉服务端，本次写结束，否则服务端会一直read
        socket.shutdownOutput();

        //接受服务端的反馈信息
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes1 = new byte[10];
        len = 0;
        System.out.println("#1 client : begin read form server...");
        while ((len = inputStream.read(bytes1)) != -1){
            byteArrayOutputStream.write(bytes1,0,len);
        }
        System.out.println(byteArrayOutputStream);

        fis.close();
        os.close();
        socket.close();
    }
}
